package com.netty;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {
    public static void main(String[] args) throws IOException {
        //线程池机制
        //思路
        //1.创建一个线程池
        //2、如果有客户端连接，就创建一个线程，与之通信
        final ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        //3.创建socket
        ServerSocket serverSocket=new ServerSocket(6666);
        System.out.println("服务器启动 了");
        while (true){
            //监听，等待客户端连接
            final Socket socket=serverSocket.accept();
            System.out.println("连接到一个客户端");
            newCachedThreadPool.execute(new Runnable() {
                public void run() {
                    //重写runnable方法
                    //可以和客户端通讯
                    handler(socket);

                }
            });
        }

    }
    public static void handler(Socket socket){
        try {
            System.out.println("线程信息 id="+Thread.currentThread().getId()+",名字="+Thread.currentThread().getName());
            byte[] bytes=new byte[1024];
            InputStream inputStream=socket.getInputStream();//通过socket获取输入流
            //循环的读取客户端发送的数据
            while (true){
                System.out.println("线程id="+Thread.currentThread().getId()+",名字="+Thread.currentThread().getName());
                int read = inputStream.read(bytes);
                if (read!=-1){
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        }catch (IOException e){

        }
    }
}
